package com.zdc.learn.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 在线多个客户端交流
 */
public class GroupServer {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();

            ServerBootstrap channel = bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //可连接的连接数 队列（对应tcp/ip 协议）
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //handler 客户端连接之前处理
                    //.handler(null)
                    //childHandler 处理客户端连接之后的请求
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //解码器
                            pipeline.addLast("decoder",new StringDecoder());
                            //编码器
                            pipeline.addLast("encoder",new StringEncoder());
                            //业务处理器
                            pipeline.addLast(new GroupServerChatHandler());
                        }
                    });
            System.out.println("服务启动.....................");
            ChannelFuture future = channel.bind(6666).sync();
            Scanner scanner = new Scanner(System.in);
            if (scanner.hasNextLine()){
                future.channel().writeAndFlush(scanner.nextLine());
            }

            //监听关闭
            future.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }
}
